package cn.itrip.utlis;

import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

public class RedisUtils {

    /**
     * 注入RedisTemplate實例
     */
    private RedisTemplate<Serializable,Object> redisTemplate;

    /**
     * 保存
     * @param key
     * @param value
     * @return
     */
    public Boolean set(String key,String value){
        try {
            redisTemplate.opsForValue().set(key,value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 保存，時間單位為毫秒
     * @param key
     * @param value
     * @param time
     * @return
     */
    public Boolean set(String key,String value,Long time){
        try {
            redisTemplate.opsForValue().set(key,value,time, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 根據key 取值
     * @param key
     * @return
     */
    public String getValue(String key){
        String value = null;
        try {
           value = (String) redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return value;
    }

    /**
     * 查詢剩餘時間
     * @param key
     * @return
     */
    public Long getResidueTime(String key){
        Long log = -1L;
        try {
            log=redisTemplate.opsForValue().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return -3L;
        }
        return log;
    }

    /**
     * 刪除
     * @param key
     * @return
     */
     public Boolean delete(String key){
         try {
             redisTemplate.delete(key);
         } catch (Exception e) {
             e.printStackTrace();
             return false;
         }
         return true;
     }

    public RedisTemplate<Serializable, Object> getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}
